package oceanwiki.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @FileName LoginInterceptor
 * @Description
 * @Author Me
 * @date 2024-09-18
 **/

@Component
public class LoginInterceptor implements HandlerInterceptor {
    private static final Logger LOG = LoggerFactory.getLogger(LoginInterceptor.class);

    @Resource
    private RedisTemplate redisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //打印请求信息
        LOG.info("------------------------LoginInterceptor开始-----------------------------");
        Long startTime = System.currentTimeMillis();
        request.setAttribute("requestStartTime", startTime);

        //OPTIONS请求 做预检
        if (request.getMethod().toUpperCase().equals("OPTIONS")) {
            //如果是这个方法则直接放行
            return true;
        }
        String path = request.getRequestURI().toString();
        LOG.info("接口登录拦截，path:{}", path);

        //获取请求头的token
        String token = request.getHeader("token");
        LOG.info("登录校验开始，token：{}", token);

        if (token==null || token.isEmpty()){
            LOG.info("token为空，请求被拦截");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        Object object = redisTemplate.opsForValue().get(token);
        if (object == null) {
            LOG.warn("token无效，请求被拦截");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        else {
            LOG.info("已登录：{}", object);
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        Long startTime = (Long) request.getAttribute("requestStartTime");
        LOG.info("---------------------------LoginInterceptor结束 耗时：{}ms----------------------------------", System.currentTimeMillis()-startTime);

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
